<template>
	<view>
		<u-upload class="" uploadIcon="plus" :disabled="disabled" :maxCount="limit" :width="width" :height="height"
			:capture="capture" :fileList.sync="images" :deletable="deletable" :multiple="multiple"
			:deletePosition="deteleIconPosition" @afterRead="afterRead" @delete="deletePic" :previewFullImage="preview">
			<view :style="{'width':width,'height':height}">
				<slot></slot>
			</view>
		</u-upload>
		<Toast></Toast>
	</view>
</template>

<script>
	import upload from '@/utils/upload';
	export default {
		name: 'upload-image',
		options: {
			styleIsolation: 'shared' // 解除样式隔离
		},
		props: {
			disabled: {
				type: Boolean,
				default: false
			},
			preview: {
				type: Boolean,
				default: true
			},
			deletable: {
				type: Boolean,
				default: true
			},
			multiple: {
				type: Boolean,
				default: false
			},
			value: {
				type: [String, Array],
				default: ''
			},
			capture: {
				type: [Array, String],
				default: () => ['album', 'camera']
			},
			// 文件类型, 例如['png', 'jpg', 'jpeg']
			fileType: {
				type: Array,
				default: () => ['png', 'jpg', 'jpeg', 'webp']
			},
			// 大小限制(MB)
			fileSize: {
				type: Number,
				default: 20
			},
			// 图片数量
			limit: {
				type: Number,
				default: 1
			},
			width: {
				type: [Number, String],
				default: '66px'
			},
			height: {
				type: [Number, String],
				default: '66px'
			},
			deletePosition: {
				type: String,
				default: 'bottomCenter'
			}
		},
		data() {
			return {
				assetsPath: getApp().globalData.config.assetsPath,
				images: [],
				uploadList: []
			};
		},
		computed: {
			deteleIconPosition() {
				return this.deletePosition
			}
		},
		watch: {
			value: {
				handler(val) {
					if (val) {
						// 首先将值转为数组
						const list = Array.isArray(val) ? val : val.split(',');
						this.uploadList = list;
						// 然后将数组转为对象数组
						this.images = list.map(item => {
							item = item.includes(this.assetsPath) ? item.replace(this.assetsPath, '') : item;
							if (typeof item === 'string') {
								item = {
									name: this.assetsPath + item,
									url: this.assetsPath + item,
									status: 'success'
								};
							}
							return item;
						});
					} else {
						this.uploadList = [];
						this.images = [];
						return [];
					}
				},
				deep: true,
				immediate: true
			},
			uploadList: {
				handler(val) {
					this.$emit('input', val.toString());
				}
			}
		},
		methods: {
			// 删除图片
			deletePic(event) {
				if (this.images.length === this.uploadList.length) this.uploadList.splice(event.index, 1);
				// this.uploadList.splice(event.index, 1);
				this.images.splice(event.index, 1);
			},
			// 选择图片
			async afterRead(event) {
				const {
					file
				} = event;
				if (!this.uploadFileValidate(file)) return false;
				this.$modal.loading('正在上传图片');
				if (this.multiple) {
					if (file.length > this.limit) {
						file.splice(this.limit, -1)
					}
					for (let item of file) {
						this.images.push({
							...item,
							status: 'uploading',
							message: '上传中'
						});
						this.uploadFilePromise(item.url);
					}
				} else {
					this.images.push({
						...file,
						status: 'uploading',
						message: '上传中'
					});
					this.uploadFilePromise(file.url);
					this.$emit('rawData', file.url)
				}
			},
			// 校验文件
			uploadFileValidate(file) {
				// 如果 this.multiple 为 true，file 是一个数组
				if (this.multiple && Array.isArray(file)) {
					// 遍历数组中的每个文件
					for (let i = 0; i < file.length; i++) {
						const singleFile = file[i];
						// 对每个文件进行校验
						if (!this.validateSingleFile(singleFile)) {
							return false; // 如果任何一个文件校验失败，返回 false
						}
					}
					return true; // 所有文件都校验通过
				} else {
					// 如果 this.multiple 为 false，file 是单个文件
					return this.validateSingleFile(file);
				}
			},
			// 校验单个文件的方法
			validateSingleFile(file) {
				let isImg = false;
				if (this.fileType.length) {
					let fileExtension = '';
					let fileUrl = file.name ? file.name : file.url;
					if (fileUrl.lastIndexOf('.') > -1) {
						fileExtension = fileUrl.slice(fileUrl.lastIndexOf('.') + 1);
						// 文件类型转换为小写 兼容IOS
						fileExtension = fileExtension.toLowerCase();
					}
					isImg = this.fileType.some(type => {
						if (file.type.indexOf(type) > -1) return true;
						if (fileExtension && fileExtension.indexOf(type) > -1) return true;
						return false;
					});
				} else {
					isImg = file.type.indexOf('image') > -1;
				}
				if (!isImg) {
					this.$toast(`文件格式不正确, 请上传${this.fileType.join('/')}图片格式文件`);
					return false;
				}
				if (this.fileSize) {
					const isLt = file.size / 1024 / 1024 < this.fileSize;
					if (!isLt) {
						this.$toast(`上传的图片过不能超过${fileSize}MB`);
						return false;
					}
				}
				return true;
			},
			// 上传图片
			uploadFilePromise(url) {
				let fileListLen = (this.images.length || 1) - 1;
				upload({
						url: '/technicianapp/Index/uploadImage',
						filePath: url
					})
					.then(res => {
						this.$modal.closeLoading();
						this.uploadFileSuccess(res.data.url, fileListLen);
					})
					.catch(err => {
						this.$modal.closeLoading();
						this.$modal.msgError('上传失败');
						this.deletePic({
							index: fileListLen
						});
					});
			},
			// 上传成功
			uploadFileSuccess(url, idx) {
				this.$set(this.images, idx, {
					status: 'success',
					message: '成功',
					url
				});
				this.$modal.closeLoading();
				this.uploadList.push(url);
			}
		}
	};
</script>

<style lang="scss" scoped>
	::v-deep .u-upload {
		.u-upload__wrap {
			padding: -8px;

			.u-upload__wrap__preview,
			.u-upload__button {
				// margin: 8px 8px 8px 0;
			}

			.u-upload__deletable {
				height: 20px;
				width: 20px;

				.u-upload__deletable__icon {
					transform: scale(0.9);
					top: 10%;
					right: 10%;
				}
			}
		}
	}

	::v-deep .u-upload__button {
		margin: 0 !important;
	}
</style>